package com.rt.system.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.alibaba.fastjson.JSON;
import com.rt.common.exception.ServiceException;
import com.rt.common.utils.DateUtils;
import com.rt.common.utils.StringUtils;
import com.rt.system.domain.*;
import com.rt.system.mapper.RtAssemblyInfoMapper;
import com.rt.system.mapper.RtExamPaperQuestionsMapper;
import com.rt.system.mapper.RtQuestionsInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rt.system.mapper.RtExamPaperInfoMapper;
import com.rt.system.service.IRtExamPaperInfoService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 试卷信息Service业务层处理
 * 
 * @author Yg
 * @date 2022-05-09
 */
@Service
public class RtExamPaperInfoServiceImpl implements IRtExamPaperInfoService 
{
    @Autowired
    private RtExamPaperInfoMapper rtExamPaperInfoMapper;

    @Autowired
    private RtAssemblyInfoMapper rtAssemblyInfoMapper;

    @Autowired
    private RtExamPaperQuestionsMapper rtExamPaperQuestionsMapper;

    @Autowired
    private RtQuestionsInfoMapper rtQuestionsInfoMapper;

    @Autowired
    private RtQuestionsInfoServiceImpl rtQuestionsInfoService;

    /**
     * 查询试卷信息
     * 
     * @param id 试卷信息主键
     * @return 试卷信息
     */
    @Override
    public RtExamPaperInfo selectRtExamPaperInfoById(Long id)
    {
        return rtExamPaperInfoMapper.selectRtExamPaperInfoById(id);
    }

    /**
     * 查询试卷信息列表
     * 
     * @param rtExamPaperInfo 试卷信息
     * @return 试卷信息
     */
    @Override
    public List<RtExamPaperInfo> selectRtExamPaperInfoList(RtExamPaperInfo rtExamPaperInfo)
    {
        return rtExamPaperInfoMapper.selectRtExamPaperInfoList(rtExamPaperInfo);
    }

    /**
     * 新增试卷信息
     * 
     * @param rtExamPaperInfo 试卷信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertRtExamPaperInfo(RtExamPaperInfo rtExamPaperInfo)
    {
        try {
            // 查询出策略
            RtAssemblyInfo rtAssemblyInfo = rtAssemblyInfoMapper.selectRtAssemblyInfoById(rtExamPaperInfo.getAssemblyId());
            // 新增试卷信息
            rtExamPaperInfo.setCreateTime(DateUtils.getNowDate());
            rtExamPaperInfo.setAssemblyId(rtAssemblyInfo.getId());
            rtExamPaperInfo.setDifficulty(rtAssemblyInfo.getDifficultyDegree());
            rtExamPaperInfo.setTotal(rtAssemblyInfo.getTotalQuestions());
            rtExamPaperInfo.setTotalScore(rtAssemblyInfo.getTotalScore());
            rtExamPaperInfoMapper.insertRtExamPaperInfo(rtExamPaperInfo);
            // 根据科目查询试题列表
            List<RtQuestionsInfo> rtQuestionsInfos = rtQuestionsInfoMapper.selectRtExamQuestionsInfoList(rtAssemblyInfo.getSubjectId(),rtAssemblyInfo.getBelongArea());
            // 题型列表
            List<RtAssemblyConf> rtAssemblyConfs = rtAssemblyInfo.getRtAssemblyConfs();
            // 知识点
            List<RtAssemblyKnowledge> rtAssemblyKnowledges = rtAssemblyInfo.getRtAssemblyKnowledges();
            // 难易度
            List<RtAssemblyDifficulty> rtAssemblyDifficulties = rtAssemblyInfo.getRtAssemblyDifficulties();
            // 试题id集
            List<RtExamPaperQuestions> result = new ArrayList<>();
            // 分值
            BigDecimal sum =new BigDecimal("0");
            for (RtQuestionsInfo rtQuestionsInfo : rtQuestionsInfos) {
                // 控制循环
                Boolean choose=true;
                for (RtAssemblyConf rtAssemblyConf : rtAssemblyConfs) {
                    if (StringUtils.isNull(rtAssemblyConf.getQuestionTypeModuleId()) ? rtQuestionsInfo.getQuestionTypeId()==rtAssemblyConf.getQuestionTypeId() : (rtQuestionsInfo.getQuestionTypeId()==rtAssemblyConf.getQuestionTypeId() && rtQuestionsInfo.getQuestionModuleId()==rtAssemblyConf.getQuestionTypeModuleId())){
                        sum=rtAssemblyConf.getSingleScore();
                        System.out.println(rtQuestionsInfo.getId()+"符合题型");
                        choose=false;
                    }
                }
                // 如果进入说明不符合条件
                if (choose)continue;
                // 如果符合进行下一轮
                choose=true;
                // 可为空
                if (rtAssemblyKnowledges.size()==0){
                    System.out.println(rtQuestionsInfo.getId()+"知识点为空不做校验");
                    choose=false;
                }
                // 不为空情况
                for (RtAssemblyKnowledge rtAssemblyKnowledge : rtAssemblyKnowledges) {
                    if (rtAssemblyKnowledge.getKnowledgeId().equals(rtQuestionsInfo.getKnowledgeId())){
                        System.out.println(rtQuestionsInfo.getId()+"符合知识点");
                        choose=false;
                    }
                }
                // 如果进入说明不符合条件
                if (choose)continue;
                // 如果符合进行下一轮
                choose=true;
                // 可为空
                if (rtAssemblyDifficulties.size()==0){
                    System.out.println(rtQuestionsInfo.getId()+"难易度为空不做校验");
                    choose=false;
                }
                for (RtAssemblyDifficulty rtAssemblyDifficulty : rtAssemblyDifficulties) {
                    if (rtQuestionsInfo.getDifficulty().equals(rtAssemblyDifficulty.getDifficulty())){
                        System.out.println(rtQuestionsInfo.getId()+"符合难易度");
                        choose=false;
                    }
                }
                // 全部符合条件
                if (!choose){
                    // 根据条件判断已全部拿完该题型
                    setCount(rtAssemblyConfs,rtAssemblyKnowledges,rtAssemblyDifficulties,rtQuestionsInfo);
                    RtExamPaperQuestions rtExamPaperQuestions = new RtExamPaperQuestions();
                    rtExamPaperQuestions.setQuestionId(rtQuestionsInfo.getId());
                    rtExamPaperQuestions.setExamPaperId(rtExamPaperInfo.getId());
                    rtExamPaperQuestions.setScore(sum);
                    result.add(rtExamPaperQuestions);
                }
                // 如果已拿完就结束循环
                if (result.size()==rtAssemblyInfo.getTotalQuestions()){
                    break;
                }
            }
            // 判断题数是否足够
            if (result.size()!=rtAssemblyInfo.getTotalQuestions()){
                throw new ServiceException("题数不足！");
            }else {
                for (RtExamPaperQuestions rtExamPaperQuestions : result) {
                    rtExamPaperQuestionsMapper.insertRtExamPaperQuestions(rtExamPaperQuestions);
                }
            }
        }catch (Exception e){
            System.out.println(e.toString());
            throw new ServiceException("题数不足！");
        }
        return 1;
    }

    public void setCount(List<RtAssemblyConf> rtAssemblyConfs,List<RtAssemblyKnowledge> rtAssemblyKnowledges,List<RtAssemblyDifficulty> rtAssemblyDifficulties,RtQuestionsInfo rtQuestionsInfo) {
        for (int i = 0; i < rtAssemblyKnowledges.size(); i++) {
            if (rtAssemblyKnowledges.get(i).getKnowledgeId().equals(rtQuestionsInfo.getKnowledgeId()) ){
                rtAssemblyKnowledges.get(i).setCount(rtAssemblyKnowledges.get(i).getCount()-1);
                if (rtAssemblyKnowledges.get(i).getCount()==0){
                    rtAssemblyKnowledges.remove(i);
                }
            }
        }
        for (int i = 0; i < rtAssemblyConfs.size(); i++) {
            if (StringUtils.isNull(rtAssemblyConfs.get(i).getQuestionTypeModuleId()) ?rtAssemblyConfs.get(i).getQuestionTypeId()== rtQuestionsInfo.getQuestionTypeId() : (rtAssemblyConfs.get(i).getQuestionTypeId()== rtQuestionsInfo.getQuestionTypeId() && rtAssemblyConfs.get(i).getQuestionTypeModuleId()==rtQuestionsInfo.getQuestionModuleId())){
                rtAssemblyConfs.get(i).setCount(rtAssemblyConfs.get(i).getCount()-1);
                if (rtAssemblyConfs.get(i).getCount()==0){
                    rtAssemblyConfs.remove(i);
                }
            }
        }
        for (int i = 0; i < rtAssemblyDifficulties.size(); i++) {
            if (rtAssemblyDifficulties.get(i).getDifficulty().equals(rtQuestionsInfo.getDifficulty()) ){
                rtAssemblyDifficulties.get(i).setCount(rtAssemblyDifficulties.get(i).getCount()-1);
                if (rtAssemblyDifficulties.get(i).getCount()==0){
                    rtAssemblyDifficulties.remove(i);
                }
            }
        }
    }
    /**
     * 修改试卷信息
     * 
     * @param rtExamPaperInfo 试卷信息
     * @return 结果
     */
    @Override
    public int updateRtExamPaperInfo(RtExamPaperInfo rtExamPaperInfo)
    {
        return rtExamPaperInfoMapper.updateRtExamPaperInfo(rtExamPaperInfo);
    }

    /**
     * 批量删除试卷信息
     * 
     * @param ids 需要删除的试卷信息主键
     * @return 结果
     */
    @Override
    public int deleteRtExamPaperInfoByIds(Long[] ids)
    {
        return rtExamPaperInfoMapper.deleteRtExamPaperInfoByIds(ids);
    }

    /**
     * 删除试卷信息信息
     * 
     * @param id 试卷信息主键
     * @return 结果
     */
    @Override
    public int deleteRtExamPaperInfoById(Long id)
    {
        return rtExamPaperInfoMapper.deleteRtExamPaperInfoById(id);
    }

    @Override
    public List<RtQuestionsInfo> selectRtExamQyestinsInfoList(Long id) {
        List<RtQuestionsInfo> rtQuestionsInfos = new ArrayList<>();
        RtExamPaperQuestions rtExamPaperQuestions = new RtExamPaperQuestions();
        rtExamPaperQuestions.setExamPaperId(id);
        // 先查出关联表
        List<RtExamPaperQuestions> examPaperQuestions = rtExamPaperQuestionsMapper.selectRtExamPaperQuestionsList(rtExamPaperQuestions);
        for (RtExamPaperQuestions examPaperQuestion : examPaperQuestions) {
            RtQuestionsInfo rtQuestionsInfoById = rtQuestionsInfoService.selectRtQuestionsInfoById(examPaperQuestion.getQuestionId());
            if (StringUtils.isNotNull(rtQuestionsInfoById)){
                rtQuestionsInfos.add(rtQuestionsInfoById);
            }
        }
        // 排序
        return rtQuestionsInfos.stream().sorted(Comparator.comparing(RtQuestionsInfo::getKnowledgeId)).collect(Collectors.toList());
    }

    @Override
    public int releaseRtExamPaperInfo(RtExamPaperInfo rtExamPaperInfo) {
        return 0;
    }

    @Override
    public List<RtQuestionsInfo> selectRtExamPaperDuplicateList(Long id) {
        List<RtQuestionsInfo> rtQuestionsInfos = selectRtExamQyestinsInfoList(id);
        ArrayList<RtQuestionsInfo> list = new ArrayList<>();
        int count=0;
        for (int i = 0; i < rtQuestionsInfos.size(); i++) {
            for(int j =i+1;j<rtQuestionsInfos.size();j++) {
                if(rtQuestionsInfos.get(i).getQuestionsContent().replaceAll("<[.[^<]]*>", "").contains(rtQuestionsInfos.get(j).getQuestionsContent().replaceAll("<[.[^<]]*>", ""))) {
                    count++;//计数器
                }
                if(rtQuestionsInfos.get(j).getQuestionsContent().replaceAll("<[.[^<]]*>", "").contains(rtQuestionsInfos.get(i).getQuestionsContent().replaceAll("<[.[^<]]*>", ""))) {
                    count++;//计数器
                }
                if(count>=1 && rtQuestionsInfos.get(i).getQuestionsContent().replaceAll("<[.[^<]]*>", "").length()!=0 && rtQuestionsInfos.get(j).getQuestionsContent().replaceAll("<[.[^<]]*>", "").length()!=0){
                    list.add(rtQuestionsInfos.get(i));
                    list.add(rtQuestionsInfos.get(j));
                }
                count = 0;//计算器置为0
            }
        }
        return list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(RtQuestionsInfo ::getId))), ArrayList::new));
    }

    @Override
    public List<RtExamPaper> selectRtExamQyestinsInfoListExcle(Long[] ids) {
        List<RtExamPaper> rtExamPapers = rtExamPaperInfoMapper.selectRtExamQyestinsInfoListExcle(ids);
        for (RtExamPaper rtExamPaper : rtExamPapers) {
            rtExamPaper.setQuestionsContent(rtExamPaper.getQuestionsContent().replaceAll("<(?!img)[^>]*>", ""));
            if (rtExamPaper.getQuestionTypeId()==4)rtExamPaper.setIsAnswer(rtExamPaper.getIsCorrect());
            if (rtExamPaper.getRemark()!=null) rtExamPaper.setRemark(rtExamPaper.getRemark().replaceAll("<(?!img)[^>]*>", ""));
            if (!rtExamPaper.getParentId().equals("0")) rtExamPaper.setScore(null);
        }
        return rtExamPapers;
    }

    @Override
    public List<RtQuestionsInfo> selectRtExamQyestinsInfoListIds(Long[] ids) {
        List<RtQuestionsInfo> rtQuestionsInfos = new ArrayList<>();
        // 先查出关联表
        List<RtExamPaperQuestions> examPaperQuestions = rtExamPaperQuestionsMapper.selectRtExamQyestinsInfoListIds(ids);
        for (RtExamPaperQuestions examPaperQuestion : examPaperQuestions) {
            RtQuestionsInfo rtQuestionsInfoById = rtQuestionsInfoService.selectRtQuestionsInfoById(examPaperQuestion.getQuestionId());
            if (StringUtils.isNotNull(rtQuestionsInfoById)){
                rtQuestionsInfos.add(rtQuestionsInfoById);
            }
        }
        // 排序
        return rtQuestionsInfos.stream().sorted(Comparator.comparing(RtQuestionsInfo::getQuestionTypeId).thenComparing(RtQuestionsInfo::getKnowledgeId)).collect(Collectors.toList());
    }
}
